# coding: utf8
from tornado import gen

from app.base_controller import BaseController
from app.common import global_space
from app.models import Advertisement, Video, Tag, VideoType, PriceTypeDetail, VideoTime, VideoOrder, VideoCity
import logging as log

from libs.util import check_param

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


# /api/banner
class Banner(BaseController):

    @gen.coroutine
    def get(self):
        data = []
        type = self.get_argument("type", 1)
        for advertisement in Advertisement.objects.filter(state=0).filter(category_id=type).order_by('show_order').all():
            data.append(advertisement.to_dict('/750_300'))
        self.render_json(data=data)


# /api/health-check
class Health(BaseController):

    @gen.coroutine
    def get(self):
        self.render_json(data={})


# /api/video-rel
class VideoRel(BaseController):
    @gen.coroutine
    def get(self):
        vt = VideoType.objects.filter(id=self.get_argument("id", '')).first()
        vo = Video.objects.filter(video_type=vt).select_related('video_type'). \
            select_related('video_order_type'). \
            prefetch_related('video_order_type__video_time'). \
            prefetch_related('tags'). \
            prefetch_related('video_order_type__price_type_detail')
        vo = vo.order_by('show_order', '-update_time')
        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/320_210')
        return self.render_json(data=paginator)


# /api/video-detail
class VideoDetail(BaseController):
    @gen.coroutine
    def get(self):
        vid = self.get_argument("id", '')
        if not vid:
            param = [vid, ]
            if check_param(param):
                self.render_json(code=1001, msg='参数不全')
                return
        vo = Video.objects.filter(id=vid).select_related('video_type'). \
            select_related('video_order_type'). \
            prefetch_related('tags'). \
            prefetch_related('video_order_type__price_type_detail').order_by('show_order'). \
            prefetch_related('video_order_type__price_type_detail__pricetype_set').order_by('show_order'). \
            prefetch_related('video_order_type__price_type_detail__pricetype_set__price_type_detail').order_by('show_order').first()
        return self.render_json(data=vo.to_dict(photo_style='/710_476', type=2))


# /api/video-play
class VideoPlay(BaseController):
    @gen.coroutine
    def get(self):
        vid = self.get_argument("id", '')
        if not vid:
            param = [vid, ]
            if check_param(param):
                self.render_json(code=1001, msg='参数不全')
                return
        vo = Video.objects.filter(id=vid).first()
        vo.play_time += 1
        vo.save()
        return self.render_json(data={'url': vo.url})


# /api/video-city
class City(BaseController):

    @gen.coroutine
    def get(self):
        return self.render_json(data=[key.to_dict() for key in VideoCity.objects.filter(state=0).all()])


# /api/video-list
class IndexVideos(BaseController):

    @gen.coroutine
    def get(self):
        tag_id = self.get_argument("tag", '')
        if tag_id:
            tag = Tag.objects.filter(id=tag_id).order_by('show_order').first()
        else:
            tag = Tag.objects.order_by('show_order').first()
        vo = tag.video_set.filter(state=0).select_related('video_type'). \
            select_related('video_order_type'). \
            prefetch_related('video_order_type__video_time'). \
            prefetch_related('tags'). \
            prefetch_related('video_order_type__price_type_detail')

        order = self.get_argument("order", '')
        if order and 'play_time' in order:
            vo = vo.order_by(order)
        elif 'price' in order:
            _list = [key.to_dict(photo_style='/710_476') for key in vo.all()]
            if order == 'price':
                _list.sort(key=lambda k: (k.get('transaction_price')))
            if order == '-price':
                _list.sort(key=lambda k: (-k.get('transaction_price')))
            paginator = self.pagination_list(object_list=_list, page_num=int(self.get_argument("pageNum", 1)))
            return self.render_json(data=paginator)
        else:
            vo = vo.order_by('show_order', '-update_time')

        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
        return self.render_json(data=paginator)


# /api/video-search
class VideoSearch(BaseController):

    @gen.coroutine
    def get(self):
        vo = Video.objects.filter(state=0)
        title = self.get_argument("title", '')
        if title:
            vo = vo.filter(name__contains=title).select_related('video_type'). \
                select_related('video_order_type'). \
                prefetch_related('video_order_type__video_time'). \
                prefetch_related('tags'). \
                prefetch_related('video_order_type__price_type_detail')
        vo = vo.order_by('show_order', '-update_time')
        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/320_210')
        return self.render_json(data=paginator)


# /api/all-tags
class AllTags(BaseController):
    @gen.coroutine
    def get(self):
        vo = Tag.objects.filter(state=0)
        data = [key.to_dict() for key in vo.order_by('show_order').all()]
        self.render_json(data=data)
